package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysFileInfo;
import com.ruoyi.system.service.ISysFileInfoService;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.service.ISysNoticeService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 公告 信息操作处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/notice")
public class SysNoticeController extends BaseController
{
    @Autowired
    private ISysNoticeService noticeService;

    @Resource
    private TokenService tokenService;

    @Autowired
    private ISysFileInfoService sysFileInfoService;
    /**
     * 获取通知公告列表
     */
    @PreAuthorize("@ss.hasPermi('system:notice:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysNotice notice)
    {
        startPage();
        List<SysNotice> list = noticeService.selectNoticeList(notice);
        return getDataTable(list);
    }


    /**
     * 获取通知公告列表
     */
    @GetMapping("/allList")
    public TableDataInfo allList(SysNotice notice, HttpServletRequest request)
    {
        String token = request.getHeader("Authorization");
        token = token.replaceAll("Bearer ", "");
        LoginUser userFromToken = tokenService.getUserFromToken(token);
        String userNo = userFromToken.getUser().getUserNo();
        logger.info("当前登录人： {}",userNo);
        startPage();
        notice.setVisibleRange(userNo);
        List<SysNotice> list = noticeService.selectUserAllNoticeList(notice,userNo);
        return getDataTable(list);
    }

    @GetMapping(value = "/getNotice")
    public AjaxResult getNotice(Long noticeId)
    {
        SysNotice sysNotice = noticeService.selectNoticeDetailsById(noticeId);
        String fileIds = sysNotice.getFileIds();
        List<String> fileIdList = JSON.parseObject(fileIds, List.class);
        ArrayList<SysFileInfo> filePathsList = new ArrayList<>();
        for (int i = 0; i < fileIdList.size(); i++) {
            String fileId = fileIdList.get(i);
            SysFileInfo fileInfo = sysFileInfoService.selectSysFileInfoById(fileId);
            filePathsList.add(fileInfo);
        }
        sysNotice.setFileInfo(JSON.toJSON(filePathsList));
        return AjaxResult.success(sysNotice);
    }

    @GetMapping(value = "/getNearbyNotice")
    public AjaxResult getNearbyNotice(@Param("noticeId") String noticeId, @Param("turnPage")String turnPage, HttpServletRequest request)
    {

        String token = request.getHeader("Authorization");
        token = token.replaceAll("Bearer ", "");
        LoginUser userFromToken = tokenService.getUserFromToken(token);
        String userNo = userFromToken.getUser().getUserNo();
        logger.info("当前登录人： {}",userNo);
        List<SysNotice> list = noticeService.selectUserNoticeList(userNo);
        Long newNoticeId = null;
        Long noticeIdLong = Long.parseLong(noticeId);
        if ("0".equals(turnPage)){
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getNoticeId().longValue()==noticeIdLong.longValue()&& i>=1){
                    newNoticeId =list.get(i-1).getNoticeId();
                }
            }
        }else if ("1".equals(turnPage)){
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getNoticeId().longValue()==noticeIdLong.longValue() && i<(list.size()-1)){
                    newNoticeId =list.get(i+1).getNoticeId();
                }
            }
        }else {
            logger.info("未定义翻页类型");
            return AjaxResult.success();
        }

        if (newNoticeId==null){
            logger.info("没有上一条或下一条了");
            return AjaxResult.success();
        }

        SysNotice sysNotice = noticeService.selectNoticeDetailsById(newNoticeId);
        String fileIds = sysNotice.getFileIds();
        List<String> fileIdList = JSON.parseObject(fileIds, List.class);
        ArrayList<SysFileInfo> filePathsList = new ArrayList<>();
        for (int i = 0; i < fileIdList.size(); i++) {
            String fileId = fileIdList.get(i);
            SysFileInfo fileInfo = sysFileInfoService.selectSysFileInfoById(fileId);
            filePathsList.add(fileInfo);
        }
        sysNotice.setFileInfo(JSON.toJSON(filePathsList));
        return AjaxResult.success(sysNotice);
    }

    /**
     * 根据通知公告编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:notice:query')")
    @GetMapping(value = "/{noticeId}")
    public AjaxResult getInfo(@PathVariable Long noticeId)
    {
        return AjaxResult.success(noticeService.selectNoticeById(noticeId));
    }

    /**
     * 新增通知公告
     */
    @PreAuthorize("@ss.hasPermi('system:notice:add')")
    @Log(title = "通知公告", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysNotice notice)
    {
        notice.setCreateBy(SecurityUtils.getUsername());
        return toAjax(noticeService.insertNotice(notice));
    }

    /**
     * 修改通知公告
     */
    @PreAuthorize("@ss.hasPermi('system:notice:edit')")
    @Log(title = "通知公告", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysNotice notice)
    {
        notice.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(noticeService.updateNotice(notice));
    }

    /**
     * 删除通知公告
     */
    @PreAuthorize("@ss.hasPermi('system:notice:remove')")
    @Log(title = "通知公告", businessType = BusinessType.DELETE)
    @DeleteMapping("/{noticeIds}")
    public AjaxResult remove(@PathVariable Long[] noticeIds)
    {
        return toAjax(noticeService.deleteNoticeByIds(noticeIds));
    }
}
